package com.jinyou.chengfengshop;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jinyou.chengfengshop.utils.CommonEvent;
import com.jinyou.chengfengshop.utils.CommonEventKey;
import com.sobot.chat.SobotApi;
import com.sobot.chat.api.model.Information;
import com.squareup.picasso.Picasso;
import com.jinyou.chengfengshop.Constant.AppUrl;
import com.jinyou.chengfengshop.OkHttpUtils.CallBackUtil;
import com.jinyou.chengfengshop.OkHttpUtils.OkhttpUtil;
import com.jinyou.chengfengshop.activity.AddOrderActivity;
import com.jinyou.chengfengshop.activity.LoginActivity;
import com.jinyou.chengfengshop.activity.MessageListActivity;
import com.jinyou.chengfengshop.activity.RechargeListActivity;
import com.jinyou.chengfengshop.adapter.homeViewPagerAdapter;
import com.jinyou.chengfengshop.bean.orderNoBean;
import com.jinyou.chengfengshop.homeFragment.orderDonefragment;
import com.jinyou.chengfengshop.homeFragment.orderUnDoneBfragment;
import com.jinyou.chengfengshop.homeFragment.orderUnDonefragment;
import com.jinyou.chengfengshop.homeFragment.orderUnTakefragment;
import com.jinyou.chengfengshop.mViewPager.VerticalViewPager;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {


    private TextView shop_tv;
    private CircleImageView head_img;

    private List<String> left;

    private Context mContext;
    //title的高度
    private int tHeight;
    //记录右侧当前可见的第一个item的position
    private int first = 0;
    private GridLayoutManager rightManager;
    public static Context context;
    private List<orderNoBean> odb;

    private String ShopName = "";//商家店名
    private String regionId = "";//regionId
    private String userPhone = "";//
    private String shopRegionId = "";
    private int mTest = 0;
    //计时器
    private Handler mhandle = new Handler();
    private boolean isPause = false;//是否暂停
    private long currentSecond = 0;//当前毫秒数
    private boolean recscroll = false;


    private ArrayList<Fragment> fragmentList;
    private VerticalViewPager mViewPager;


    private orderDonefragment orderA;
    private orderUnDonefragment orderB;
    private orderUnDoneBfragment orderC;
    private orderUnTakefragment orderD;


    private homeViewPagerAdapter mPagerAdapter;
    private FragmentManager mFragmentManager;


    private RadioButton wancheng_rb;
    private RadioButton send_rb;
    private RadioButton quhuo_rb;
    private RadioButton fandan_rb;

    private RadioButton fadan_rb;


    private TextView wancheng_tv;
    private TextView send_tv;
    private TextView quhuo_tv;
    private TextView fandan_tv;

    private TextView order_state_tv;
    private TextView order_address_tv;
    private TextView order_tiem_tv;
    private TextView order_id_tv;
    private TextView lv_tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SharedPreferences sh = getSharedPreferences("user", Context.MODE_PRIVATE);
        String user = sh.getString("info","");
        try {
            JSONObject usb = new JSONObject(user);
            JSONObject info = usb.getJSONObject("info");
            ShopName = info.getString("company");
            regionId = info.getString("regionId");
            shopRegionId = info.getString("shopRegionId");
            Log.i("regionId",shopRegionId);
            userPhone = info.getString("phone");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        Log.i("user",ShopName);



        context = getApplicationContext();
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        fadan_rb = (RadioButton) findViewById(R.id.fadan_rb);

        fadan_rb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent mIntent = new Intent(getApplicationContext(), AddOrderActivity.class);
                mIntent.putExtra("shopRegionId",shopRegionId);
                startActivity(mIntent);
            }
        });
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent mIntent = new Intent(getApplicationContext(), AddOrderActivity.class);
                mIntent.putExtra("shopRegionId",shopRegionId);
                startActivity(mIntent);
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setItemIconTintList(null);
        navigationView.setNavigationItemSelectedListener(this);
        head_img = (CircleImageView) navigationView.getHeaderView(0).findViewById(R.id.head_img);
        shop_tv = navigationView.getHeaderView(0).findViewById(R.id.shop_tv);
        shop_tv.setText(ShopName);
        try {
            JSONObject usb = new JSONObject(user);

            JSONObject info = usb.getJSONObject("info");
            Picasso.with(getApplicationContext())
                    .load(info.getString("img_other01"))
                    .into(head_img);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        mViewPager = (VerticalViewPager) findViewById(R.id.mViewPage);

        wancheng_rb = (RadioButton) findViewById(R.id.wancheng_rb);
        wancheng_rb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initRadiobutton();
                wancheng_rb.setChecked(true);
                mViewPager.setCurrentItem(0);
                order_state_tv.setText("已完成");
                lv_tv.setVisibility(View.INVISIBLE);
            }
        });
        send_rb = (RadioButton) findViewById(R.id.send_rb);
        send_rb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initRadiobutton();
                send_rb.setChecked(true);
                mViewPager.setCurrentItem(1);
                order_state_tv.setText("配送中");
                lv_tv.setVisibility(View.INVISIBLE);
            }
        });
        quhuo_rb = (RadioButton) findViewById(R.id.quhuo_rb);
        quhuo_rb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initRadiobutton();
                quhuo_rb.setChecked(true);
                mViewPager.setCurrentItem(2);
                order_state_tv.setText("待取货");
                lv_tv.setVisibility(View.VISIBLE);
            }
        });
        fandan_rb = (RadioButton) findViewById(R.id.fandan_rb);
        fandan_rb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initRadiobutton();
                fandan_rb.setChecked(true);
                mViewPager.setCurrentItem(3);
                order_state_tv.setText("发单中");
                lv_tv.setVisibility(View.VISIBLE);
            }
        });



        wancheng_tv = (TextView) findViewById(R.id.wancheng_tv);
        send_tv = (TextView) findViewById(R.id.send_tv);
        quhuo_tv = (TextView) findViewById(R.id.quhuo_tv);
        fandan_tv= (TextView) findViewById(R.id.fadan_tv);


        order_state_tv = (TextView) findViewById(R.id.order_state_tv);
        order_address_tv = (TextView) findViewById(R.id.order_address_tv);
        order_tiem_tv = (TextView) findViewById(R.id.order_tiem_tv);
        order_id_tv = (TextView) findViewById(R.id.order_id_tv);
        lv_tv = (TextView) findViewById(R.id.lv_tv);

        initFragmentList();
        mFragmentManager = getSupportFragmentManager();
        mPagerAdapter = new homeViewPagerAdapter(mFragmentManager,fragmentList);
        mViewPager.setAdapter(mPagerAdapter);
        mViewPager.setScrollable(false);



        new Thread(new Runnable() {
            @Override
            public void run() {
                getDoneOrder();//已完成

                getUnDoneOrder();//未完成订单

                getUnTakeOrder();//发单中
            }
        }).start();


        timeRunable.run();
        EventBus.getDefault().register(this);
    }


    private void initRadiobutton(){
        wancheng_rb.setChecked(false);
        send_rb.setChecked(false);
        quhuo_rb.setChecked(false);
        fandan_rb.setChecked(false);
    }



    //初始化各个fragment
    private void initFragmentList(){
        orderA =  new orderDonefragment();
        orderB = new orderUnDonefragment();
        orderC = new orderUnDoneBfragment();
        orderD = new orderUnTakefragment();
        fragmentList = new ArrayList<Fragment>();
        fragmentList.add(orderA);
        fragmentList.add(orderB);
        fragmentList.add(orderC);
        fragmentList.add(orderD);
    }


    /*****************计时器*******************/
    private Runnable timeRunable = new Runnable() {
        @Override
        public void run() {

            currentSecond = currentSecond + 1000;
            //timerText.setText(TimeUtil.getFormatHMS(currentSecond));

            Log.d("Main",getFormatHMS(currentSecond));
            if(currentSecond%5000 == 0){

                getDoneOrder();//已完成

                getUnDoneOrder();//未完成订单


                getUnTakeOrder();//发单中
                mTest++;

            }
            //
            if (!isPause) {
                //递归调用本runable对象，实现每隔一秒一次执行任务
                mhandle.postDelayed(this, 1000);
            }
        }
    };
    /**
     * 根据毫秒返回时分秒
     * @param time
     * @return
     */
    public static String getFormatHMS(long time){
        time=time/1000;//总秒数
        int s= (int) (time%60);//秒
        int m= (int) (time/60);//分
        int h=(int) (time/3600);//秒
        return String.format("%02d:%02d:%02d",h,m,s);
    }


    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.start, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_wallet) {
            // Handle the camera action
            Intent mIntent = new Intent(getApplicationContext(),RechargeListActivity.class);
            startActivity(mIntent);
        } else if (id == R.id.nav_order) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_message) {
            Intent mIntent = new Intent(getApplicationContext(),MessageListActivity.class);
            startActivity(mIntent);
        } else if (id == R.id.nav_feed) {
            Information info = new Information();
            info.setAppkey("1c37f0bc0a564ea6bac70e1053e07cca");
            info.setUname(ShopName);
            info.setUid(regionId);
            info.setTel(userPhone);

            /**
             * @param context 上下文对象
             * @param information 初始化参数
             */

            SobotApi.startSobotChat(context, info);
        }else if (id == R.id.nav_ext) {
            reLogin();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }



    private String formatData(String dataFormat, long timeStamp) {
        if (timeStamp == 0) {
            return "";
        }

        String mm = timeStamp+"";
        mm = mm.substring(0,10);
        timeStamp = Long.parseLong(mm);

        timeStamp = timeStamp * 1000;
        String result = "";
        SimpleDateFormat format = new SimpleDateFormat(dataFormat);
        result = format.format(new Date(timeStamp));
        return result;
    }

    //重新登陆
    private void reLogin(){
//        timeRunable.
        SharedPreferences sh = getSharedPreferences("user", Context.MODE_PRIVATE);
        SharedPreferences.Editor edt = sh.edit();
        edt.putString("tocken","");
        edt.putString("info","");
        edt.commit();
        Intent mIntent = new Intent(MainActivity.this,LoginActivity.class);
        startActivity(mIntent);
        finish();
    }



    //获取未完成订单列表---已完成
    private void getDoneOrder(){
        HashMap<String,String> paramsMap = new HashMap<>();
        SharedPreferences sh = getSharedPreferences("user", Context.MODE_PRIVATE);
        String tocken = sh.getString("tocken","");
        paramsMap.put("token",tocken);
        paramsMap.put("sysCustomer","o2o-chengfeng");
        OkhttpUtil.okHttpPost(AppUrl.ORDER_LIST_DONE, paramsMap, new CallBackUtil.CallBackString() {
            @Override
            public void onFailure(Call call, Exception e) {

            }

            @Override
            public void onResponse(String response) {//请求成功时调用，执行在UI线程
                try {
                    JSONObject obj = new JSONObject(response);
                    int code = obj.getInt("status");

                    if(code == 1){
                        int total = obj.getInt("totalCount");//已完成数量

                        if(total>0){
                            wancheng_tv.setText(total+"");
                            wancheng_tv.setVisibility(View.VISIBLE);
                        }else {
                            wancheng_tv.setVisibility(View.INVISIBLE);
                        }

                    }else {
                        if(obj.getString("type").equals("notLogin")){
                            reLogin();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }


    //获取未完成订单列表---未完成
    private void getUnDoneOrder(){
        HashMap<String,String> paramsMap = new HashMap<>();
        SharedPreferences sh = getSharedPreferences("user", Context.MODE_PRIVATE);
        String tocken = sh.getString("tocken","");
        paramsMap.put("token",tocken);
        paramsMap.put("sysCustomer","o2o-chengfeng");
        OkhttpUtil.okHttpPost(AppUrl.ORDER_LIST_UNDONE, paramsMap, new CallBackUtil.CallBackString() {
            @Override
            public void onFailure(Call call, Exception e) {

            }

            @Override
            public void onResponse(String response) {//请求成功时调用，执行在UI线程
                try {
                    JSONObject obj = new JSONObject(response);
                    int code = obj.getInt("status");

                    if(code == 1){
                        int total = obj.getInt("size");//已完成数量
                        String ob = obj.getString("data");

                        if (ob != null && !ob.equals("")) {
                            Type typeOfT = new TypeToken<List<orderNoBean>>() {
                            }.getType();
                            odb = new Gson().fromJson(ob, typeOfT);

                            int unSend = 0;//配送中
                            int unPack = 0;//接单未取货

                            for(orderNoBean mo:odb){
                                if(mo.getOrderType() == 59){
                                    unPack++;
                                }else{
                                    unSend++;
                                }
                            }
                            if(unSend>0){
                                send_tv.setText(unSend+"");
                                send_tv.setVisibility(View.VISIBLE);
                            }else {
                                send_tv.setVisibility(View.GONE);
                            }


                            if(unPack>0){
                                quhuo_tv.setText(unPack+"");
                                quhuo_tv.setVisibility(View.VISIBLE);
                            }else {
                                quhuo_tv.setVisibility(View.GONE);
                            }

                        }


                    }else {

                        Toast.makeText(getApplicationContext(),obj.getString("error"),Toast.LENGTH_SHORT).show();
                        if(obj.getString("type").equals("notLogin")){
                            reLogin();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }
    //获取未完成订单列表---发单中
    private void getUnTakeOrder(){
        HashMap<String,String> paramsMap = new HashMap<>();
        SharedPreferences sh = getSharedPreferences("user", Context.MODE_PRIVATE);
        final String tocken = sh.getString("tocken","");
        paramsMap.put("token",tocken);
        paramsMap.put("sysCustomer","o2o-chengfeng");
        OkhttpUtil.okHttpPost(AppUrl.ORDER_LIST_UNTAKE, paramsMap, new CallBackUtil.CallBackString() {
            @Override
            public void onFailure(Call call, Exception e) {

            }

            @Override
            public void onResponse(String response) {//请求成功时调用，执行在UI线程
                try {
                    JSONObject obj = new JSONObject(response);
                    int code = obj.getInt("status");

                    if(code == 1){
                        int total = obj.getInt("size");//已完成数量
                        fandan_tv.setText(total+"");
                        if(total>0){
                            fandan_tv.setVisibility(View.VISIBLE);
                        }else {
                            fandan_tv.setVisibility(View.INVISIBLE);
                        }

                    }else {

                        Toast.makeText(getApplication(),obj.getString("error"),Toast.LENGTH_SHORT).show();
                        if(obj.getString("type").equals("notLogin")){
                            reLogin();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }




    @Override
    protected void onResume() {
        super.onResume();
        isPause = false;
        //timeRunable.run();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //timeRunable.
        EventBus.getDefault().unregister(this);
    }


    @Override
    protected void onPause() {
        super.onPause();
        isPause = true;
    }

    public void onEventMainThread(CommonEvent event) {
        switch (event.getKey()) {
            case CommonEventKey.HOME_ORDER_CHANGE: //订单改变
                SharedPreferences sp = getSharedPreferences("home_order",0);

                String order = sp.getString("order","");
                String type = sp.getString("type","");
                if(!order.equals("")){
                    try {
                        if(mViewPager.getCurrentItem() == 0){
                            if(type.equals("a")){
                                JSONObject ob = new JSONObject(order);
                                Log.i("order",order);
                                //order_address_tv.setText("");
                                order_address_tv.setText(ob.getString("riderName"));
                                String time = formatData("yyyy-MM-dd HH:mm:ss", ob.getLong("createTim"));
                                order_tiem_tv.setText(time.substring(5,time.length()));
                                order_id_tv.setText(ob.getString("orderNo"));
                            }else {

                            }
                        }

                        if(mViewPager.getCurrentItem() == 1){
                            if(type.equals("b")){
                                JSONObject ob = new JSONObject(order);
                                Log.i("order",order);
                                //order_address_tv.setText("");
                                order_address_tv.setText(ob.getString("riderName"));
                                String time = formatData("yyyy-MM-dd HH:mm:ss", ob.getLong("createTim"));
                                order_tiem_tv.setText(time.substring(5,time.length()));
                                order_id_tv.setText(ob.getString("orderNo"));
                            }else {

                            }
                        }

                        if(mViewPager.getCurrentItem() == 2){
                            if(type.equals("c")){
                                JSONObject ob = new JSONObject(order);
                                Log.i("order",order);
                                //order_address_tv.setText("");
                                order_address_tv.setText(ob.getString("riderName"));
                                String time = formatData("yyyy-MM-dd HH:mm:ss", ob.getLong("createTim"));
                                order_tiem_tv.setText(time.substring(5,time.length()));
                                order_id_tv.setText(ob.getString("orderNo"));
                            }else {

                            }
                        }

                        if(mViewPager.getCurrentItem() == 3){
                            if(type.equals("d")){
                                JSONObject ob = new JSONObject(order);
                                Log.i("order",order);
                                //order_address_tv.setText("");
                                order_address_tv.setText(ob.getString("riderName"));
                                String time = formatData("yyyy-MM-dd HH:mm:ss", ob.getLong("createTim"));
                                order_tiem_tv.setText(time.substring(5,time.length()));
                                order_id_tv.setText(ob.getString("orderNo"));
                            }else {

                            }
                        }



                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            break;
        }
    }


}
